var RUNNING_REQUEST = false;
var ajaxRequest = '';
$(document).ready(function() {

// Initialize AJAX
    var cache = new Array();
    var hashArray = new Array();
    $(window).bind('hashchange', function(e) {
        var hash = $.param.fragment();
        // Refresh is not allowed
        cache.push(hash);
        var hashArray = hash.split('/');
        navigation(hashArray);
    });
    navigation(hashArray);
    post_init(hashArray);
    login_form();
    $('.calendar_today').live('click', function() {
        var now = new Date();
        location.hash = 'choisir_date/' + timestamp_to_hybrid_date(now.getTime());
    });
    $('#select_agenda_calendar').live('change', function() {
        var dataDate = $(this).attr('data-time');
        var forceAgenda = $(this).val();
        currentData = getSessionData();
        ajax(GATEWAY_URL, {
            'query': 'choisir_date',
            'date': dataDate,
            'force_agenda': forceAgenda,
            'rdv_data': currentData
        }, function(data) {
            $('#inner-content').fadeOut().html(data).fadeIn();
            post_init();
        });
    })

    $('.switch_location').live('change', function() {
        var location_id = $(this).val();
        if ($('#shop_session').html().length) {
// Switching on calendar view, only refresh necessary data
            currentSessionData = getSessionData();
            ajax(GATEWAY_URL, {
                'query': 'check_cart_compatible',
                'shopping_session': currentData,
                'target_shop': location_id
            }, function(data) {
                if (getRest(data)['code'] == 200) {
// Rereive shop
                    ajax(GATEWAY_URL, {
                        'query': 'shop_infos',
                        'id': location_id
                    }, function(data) {
                        $('#shop-infos').fadeOut().html(restHandle(data)).fadeIn();
                        $('#shop-infos').css('float', 'left');
                        $('.book_now').hide();
                        // Update session
                        currentSessionData = getSessionData(location_id);
                    }, function() {
// Change dates
                        ajax(GATEWAY_URL, {
                            'query': 'choisir_date',
                            'rdv_data': currentData
                        }, function(data) {
                            $('#inner-content').html(data);
                            $("#rdv-dialog").dialog("close");
                            post_init(hashArray);
                        });
                    });
                } else {
                    erraAlert(getRest(data)['message']);
                }
            });
            // Make sure everything is ok  

        } else {
            location.hash = 'boutique/' + $(this).val();
        }
    });
    $('.header a[href="#prise-rdv"]').click(function() {
        $('#profil').hide();
        $('#prise-rdv').show();
        $('.header a[href="#profil"]').css('color', 'white');
        $(this).css('color', '#2869B0');
    });
    $('.header a[href="#profil"]').click(function() {
        $('#prise-rdv').hide();
        $('#profil').show();
        $('.header a[href="#prise-rdv"]').css('color', 'white');
        $(this).css('color', '#2869B0');
    });
    $('.toggle-more-infos').live('click', function() {
        $(this).parents('.shop_class:first').find('.more-infos').slideToggle();
    });
    $('.book_this').live('click', function() {
        currentData = getSessionData();
        $('#login-content').attr('data-resa-timestamp', $(this).attr('data-resa-timestamp'));
        $('#login-content').attr('data-agenda-match', $(this).attr('data-agenda-match'));
        if (!$('#profil').html().length) {
            ajax(GATEWAY_URL, {
                'query': 'login_form'
            }, function(data) {
                $('#login-content').html(data);
                $("#login-dialog").dialog({
                    width: 400,
                    modal: true,
                    position: 'top'
                });
                post_init(hashArray);
            });
        } else {
            confirm_rdv_dialog();
        }
    });
    $('#finish-shop').live('click', function() {
        var currentData = new Array();
        currentData = getSessionData();
        // Rereive cart
        if (currentData.length) {
            ajax(GATEWAY_URL, {
                'query': 'choisir_date',
                'rdv_data': currentData
            }, function(data) {
                $('#inner-content').html(data);
                $("#rdv-dialog").dialog("close");
                post_init(hashArray);
            });
        } else {
            erraAlert('Veuillez choisir au moins une prestation');
        }
    });
    $('.close-presta').live('click', function() {
        var $prestationBloc = $(this).parents('.prestation:first');
        var $shopItem = $('#shop_session').find('input[data-uniqid="' + $prestationBloc.attr('data-uniqid') + '"]');
        var shop_url = "reserver/" + $shopItem.attr('data-shop_id');
        $prestationBloc.remove();
        $shopItem.remove();
        if ($('#shop_session').html() == '') {
            location.hash = shop_url;
        }
    });
    $('#rdv-dialog-link').live('click', function() {
        var linkArray = $(this).attr('href').split('/');
        var shop_id = linkArray[1];
        var prestation_id = linkArray[2];
        ajax(GATEWAY_URL, {
            'query': 'presta_detail',
            'shop_id': shop_id,
            'prestation_id': prestation_id
        }, function(data) {
            $('#rdv-dialog .rdv-infos').html(data);
            $("#rdv-dialog").dialog({
                closeOnEscape: false,
                open: function(event, ui) {
                    $(".ui-dialog-titlebar-close").hide();
                },
                width: 700,
                buttons: {
                    "Ajouter un rendez vous à la suite": function() {
                        var currentData = new Array();
                        $('#shop_session').append('<input type="hidden" data-shop_id="' + shop_id + '" data-presta-id="' + prestation_id + '" data-uniqid="' + uniqid() + '"/>');
                        currentData = getSessionData();
                        ajax(GATEWAY_URL, {
                            'query': 'ajouter_presta',
                            'rdv_data': currentData
                        }, function(data) {
                            $("#rdv-dialog").dialog("close");
                            $('#cart-infos').html(data);
                            post_init(hashArray);
                        });
                    },
                    "Finaliser la reservation": function() {
                        var currentData = new Array();
                        $('#shop_session').append('<input type="hidden" data-shop_id="' + shop_id + '" data-presta-id="' + prestation_id + '" data-uniqid="' + uniqid() + '"/>');
                        currentData = getSessionData();
                        // Rereive cart
                        ajax(GATEWAY_URL, {
                            'query': 'ajouter_presta',
                            'rdv_data': currentData
                        }, function(data) {
                            $('#cart-infos').html(data);
                        }, function() {
                            ajax(GATEWAY_URL, {
                                'query': 'choisir_date',
                                'rdv_data': currentData
                            }, function(data) {
                                $('#inner-content').html(data);
                                $("#rdv-dialog").dialog("close");
                                post_init(hashArray);
                            });
                        });
                    },
                    "Annuler": function() {
                        $(this).dialog("close");
                    }
                }
            });
            post_init(hashArray);
        });
        return false;
    });
});
function post_init() {
    if ($('.choose-shop-table').length) {
        $('.choose-shop-table tr').each(function() {
            $(this).find('.first-infos').height($(this).find('td:first').outerHeight() - 40); // Minus margins and paddings
        });
    }
    $('.tabs').tabs();
    $('.pointer').live('mouseenter', function() {
        $(this).css('cursor', 'pointer');
    });
    $('.pointer').live('mouseleave', function() {
        $(this).css('cursor', '');
    });
    $('.live-tipsy').tipsy({
        gravity: 'w',
        html: true
    });
    $('.live-tipsy-s').tipsy({
        gravity: 's',
        html: true
    });
}

function navigation(hashArray) {
////////////////////////////
// DISPLAY SHOP LIST
////////////////////////////
    if (hashArray[0] == 'boutique') {
        ajax(GATEWAY_URL, {
            'query': 'shop_infos',
            'id': hashArray[1]
        }, function(data) {
            $('#shop-infos').html(restHandle(data));
            $('#shop-infos').css('float', 'left');
        }, function() {
            ajax(GATEWAY_URL, {
                'query': 'shop_detail',
                'id': hashArray[1]
            }, function(data) {
                $('#inn\n\
    er-content').html(restHandle(data));
                $('#inner-content').removeClass('inner-content-separator');
                $('#cart-infos, #shop_session').html('');
                post_init();
            });
        });
        //////////////
        // BOOK
        //////////////
    } else if (hashArray[0] == 'reserver') {
        ajax(GATEWAY_URL, {
            'query': 'reserver',
            'id': hashArray[1]
        }, function(data) {
            $('#inner-content').html(restHandle(data));
            $('#inner-content').addClass('inner-content-separator');
            post_init();
            $('.book_now').remove();
        });
        ////////////////////////
        // GET PRESTATION LIST
        ////////////////////////
    } else if (hashArray[0] == 'liste_prestations') {
        currentData = getSessionData();
        ajax(GATEWAY_URL, {
            'query': 'liste_prestations',
            'rdv_data': currentData,
            'shop_id': hashArray[1],
            'presta_type_id': hashArray[2]
        }, function(data) {
            $('#inner-content').fadeOut().html(data).fadeIn();
            $('.book_now').css('display', 'none');
            $('#category_selected').attr('href', $('.book_now').attr('href'));
            post_init();
        });
        ////////////////////////
        // CHOOSE RDV DATE
        ////////////////////////
    } else if (hashArray[0] == 'choisir_date') {
        currentData = getSessionData();
        ajax(GATEWAY_URL, {
            'query': 'choisir_date',
            'date': hashArray[1],
            'rdv_data': currentData
        }, function(data) {
            $('#inner-content').fadeOut().html(data).fadeIn();
            post_init();
        });
    } else if (hashArray[0] == 'profil') {
        if (!$('#profil').html().length) {
            currentData = getSessionData();
            ajax(GATEWAY_URL, {
                'query': 'login_form'
            }, function(data) {
                $('#login-content').html(data);
                $("#login-dialog").dialog({
                    closeOnEscape: false,
                    open: function(event, ui) {
                        $(".ui-dialog-titlebar-close").hide();
                    },
                    width: 500
                });
                post_init();
                $('#login-form-object').submit(function() {
                    return false;
                });
            });
        }
    } else {
// DEFAULT NAVIGATION
        ajax(GATEWAY_URL, {
            'query': 'liste_boutiques'
        }, function(data) {
            $('#shop-infos').html(restHandle(data));
            $('#shop-infos').css('float', 'inherit');
            post_init();
            $('#cart-infos, #inner-content, #shop_session').html('');
        });
    }

}


function initializeMap(address, htmlId) {
    var geocoder;
    var map;
    var mapOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        "address": address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            erraAlert("Impossible de localiser");
        }
    });
}
